package com.bdqn.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPObject;
import com.bdqn.entity.UmsUser;
import com.bdqn.entity.responseDate.cart.OmsCartDto;
import com.bdqn.entity.responseDate.pmsProduct.PmsSkuDto;
import com.bdqn.entity.responseDate.ums.CityList;
import com.bdqn.entity.responseDate.ums.PcdListDto;
import com.bdqn.util.PcdRedisKey.GeneratePcdRedisKey;
import com.bdqn.util.cart_redis_hash.Cart_service_key;
import org.apache.ibatis.javassist.bytecode.LineNumberAttribute;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 此类是对redis数据库的操作
 */
@Component
public class Pet_service_RedisTemplate {
    //创建日志对象
    private static final Logger logger = LoggerFactory.getLogger(Pet_service_RedisTemplate.class);
    /**
     * springboot整合redis 默认使用的是lettuce客户端操作redis
     */
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //把获取到的随机token 当作key 把user对象当作value 存到redis数据库
    public String setToken(String token, UmsUser umsUser) {
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer(UmsUser.class));
        redisTemplate.opsForValue().set(token, umsUser);//把信息存到redis数据库
        return token;
    }

    //从redis数据库中通过key获取value
    public UmsUser getUser(String key) {
        try {
            String redis_key = Token_Redis_key.generateTokenRedisKey(key);
            UmsUser user = (UmsUser) redisTemplate.opsForValue().get(redis_key);
            logger.info("[REDIS] Get k-v key={}, value={}", key, user);
            return user;
        } catch (Exception e) {
            return null;
        }

    }

    //从redis中删除token
    public void delete(String token) {
        String redis_key = Token_Redis_key.generateTokenRedisKey(token);
        redisTemplate.delete(redis_key);
    }


    public OmsCartDto getCart(Long userId, PmsSkuDto pmsSkuDto) {
        /**
         * 这里使用stringRedisTemplate  因为redisTemplate的key不能序列化为字符串
         * 我们通过key和 hashKey 获取到hashValue的值
         */
        try {
            String hashKey = Cart_service_key.generateUserRedisKey(userId);
            //将hash的key和value分别是同string和json的序列化方式
            stringRedisTemplate.setHashKeySerializer(new StringRedisSerializer());
            stringRedisTemplate.setHashValueSerializer(new Jackson2JsonRedisSerializer<OmsCartDto>(OmsCartDto.class));
            OmsCartDto omsCartDto = (OmsCartDto) stringRedisTemplate.opsForHash().get(hashKey, String.valueOf(pmsSkuDto.getId()));
            logger.info("[REDIS] getHash  key={}, hashKey={}, value={}", hashKey, pmsSkuDto.getId(), omsCartDto);
            return omsCartDto;
        } catch (Exception e) {
            logger.error("[REDIS--ERROR]-->getHash 错误:{}", e);
            return null;
        }
    }

    /**
     * 以下是对存储在redis中的购物车数据的操作
     * 存储的是hash类型    hash的value就好比hashMap
     */
    public int addCart(Long userId, PmsSkuDto pmsSkuDto, OmsCartDto omsCartDto) {
        /**
         * 这里使用stringRedisTemplate  因为redisTemplate的key不能序列化为字符串
         * 所以存的uerId要toString() 转为字符串
         */
        try {
            String hashKey = Cart_service_key.generateUserRedisKey(userId);
            //将hash的key和value分别是同string和json的序列化方式
            stringRedisTemplate.setHashKeySerializer(new StringRedisSerializer());
            stringRedisTemplate.setHashValueSerializer(new Jackson2JsonRedisSerializer<OmsCartDto>(OmsCartDto.class));
            stringRedisTemplate.opsForHash().put(hashKey, pmsSkuDto.getId().toString(), omsCartDto);
            return 1;
        } catch (Exception ex) {
            logger.error("[REDIS--ERROR]-->putHash 错误:{}", ex);
            return 0;
        }
    }

    /**
     * 通过传进来的用户id  拼接完成 进行从数据库通过key 查询hash对应的value(Map)
     *
     * @param userId
     * @return
     */
    public Map<Object, Object> getHashValues(Long userId) {
        String userRedisKey = Cart_service_key.generateUserRedisKey(userId);
        //将hash的key和value分别是同string和json的序列化方式
        stringRedisTemplate.setHashKeySerializer(new StringRedisSerializer());

        stringRedisTemplate.setHashValueSerializer(new Jackson2JsonRedisSerializer<OmsCartDto>(OmsCartDto.class));
        Map<Object, Object> entries = stringRedisTemplate.opsForHash().entries(userRedisKey);
        System.out.println("======获取的所有属于userId的购物信息" + entries);
        logger.info("[REDIS] getHash  key={}, value={}", userRedisKey, entries);

        return entries;
    }

    /**
     * 通过用户传进来的id  拼接后进行从redis删除   可能同时删除好几个hashKey 所以传的数组
     */
    public int remove(Long userId, List<Long> skuIds) {
//         若传入的是数组的话 循环遍历出每个数组中的值  然后去拼接 然后进行删除
        try {
            String userRedisKey = Cart_service_key.generateUserRedisKey(userId);
            for (Long skuId : skuIds) {
                stringRedisTemplate.opsForHash().delete(userRedisKey, String.valueOf(skuId));
            }
            logger.info("[REDIS] deleteHash key={}, hashKey={}, value={}", userRedisKey, skuIds, null);
            return 1;
        } catch (Exception ex) {
            logger.error("[REDIS--ERROR]-->deleteHash 错误:{}", ex);
            return 0;
        }
    }
    /**
     * 从redis清空购物车
     */
    public int clearCart(Long userId){
        System.out.println("获取到的userId"+userId);
        try {
            String userRedisKey = Cart_service_key.generateUserRedisKey(userId);
            return 1;
        }catch (Exception e){
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 下面是存储的省市县列表集合
     */
    public int setPcdListDto(List<PcdListDto> pcdListDto) {
        try {
            String pcdRedisKey = GeneratePcdRedisKey.generatePcdRedisKey();//存储的省市县列表的key
//            redisTemplate.setKeySerializer(new StringRedisSerializer());
//            redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer(PcdListDto.class));
            String str = JSON.toJSONString(pcdListDto);
            redisTemplate.opsForValue().set(pcdRedisKey,str);
            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 下面是获取的省市县列表集合
     */
    public List<PcdListDto> getPcdListDto() {

        String pcdRedisKey = GeneratePcdRedisKey.generatePcdRedisKey();
//        redisTemplate.setKeySerializer(new StringRedisSerializer());
//       redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer(PcdListDto.class));
        Object str = redisTemplate.opsForValue().get(pcdRedisKey);
        List<PcdListDto> objects = JSON.parseArray((String) str,PcdListDto.class);
        System.out.println("从redis获取到的省市县列表信息为" + str);
        return objects;
    }
}
